<?php


namespace app\api\model;


use app\common\library\himongo;
use app\common\model\BaseModel;
use hiredis;
use common;
use ApiOper;
use think\Db;
use think\facade\Log;

class ServiceAreaModel extends BaseModel
{
    protected $name = 'service_area';
    protected $pk = 'id';

    function SERVICE_AREA_ID($city_id)
    {
        $key = 'SERVICE_AREA_ID|' . $city_id;

        $id = hiredis::db()->incr($key);
        if ($id == 1) {
            $beans =[
              'city_id' => $city_id,
              'id' => ['<','a']
            ];

            $max_id = Db::name('service_area')->where($beans)->max('maxid');

            if ($beans=== NULL) {
                $id = $city_id . "0001";
            } else {
                $id = strval(intval($max_id) + 1);
            }
            hiredis::db()->set($key, $id);
        }
        return strval($id);
    }

    function add($info)
    {
        $paramlist = [
            'city_id' => 'string',
            'name' => 'string',
            'remark' => 'string',
            'coordinates' => 'array',
            'state' => 'int',
            'creator_id' => 'string',
            'creator_name' => 'string',
            'price_rule' => 'array',
        ];


        $data = common::type_conver($info, $paramlist);
        $data['center'] = common::polygon_center($data['coordinates']);

        $data['id'] = $this->SERVICE_AREA_ID($info['city_id']);
        $data['create_time'] = date('Y-m-d H:i:s');

        ApiOper::instance()->append_creater_info($data);

        if (isset($data['price_rule'])){
            $price_rule = $data['price_rule'];
            if (is_array($price_rule) && !isset($price_rule['fee_min'])){
                $price_rule['fee_min'] = 1;
                $data['price_rule'] = $price_rule;
            }
            else if (is_array($price_rule) && empty($price_rule['fee_min'])){
                $price_rule['fee_min'] = 1;
            }
        }

        self::create($data,true);


        $this->save_to_mongo($data['city_id'], $data['id']);

        return $data;
    }

    function get_list($city_id, $condition, $pos, $limit)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'name' => 'string',
            'remark' => 'string',
            'coordinates' => 'array',
            'center' => 'array',
            'state' => 'int',
            'creator_id' => 'string',
            'create_time' => 'string',
            'creator_name' => 'string',
            'updater_id' => 'string',
            'update_time' => 'string',
            'updater_name' => 'string',
            'price_rule' => 'string',
        ];

        $beans = [
            'is_deleted' => 0
        ];
        if (!empty($city_id)) {
            $beans['city_id'] = $city_id;
        }
        if (isset($condition['state'])) {
            $beans['state'] = $condition['state'];
        }

        if (!empty($condition['sk'])) {
            $beans['name'] = $condition['sk'];
        }


        $rows = $this->where($beans)->field(common::array_keys($selectlist))->limit($pos,$limit)->select();
        Log::info("serva result:{$rows}");
        if ($rows->isEmpty()){
            return [];
        }
        else{
            return $rows->toArray();
        }
    }


    function count($city_id, $condition)
    {
        $st = "select count(1) as total from tb_service_area where   city_id = ?";

        $beans = [
            'city_id' => $city_id,
        ];
        if (isset($condition['state'])) {
            $beans['state'] = $condition['state'];
        }

        if (!empty($condition['sk'])) {
            $beans['name'] = $condition['sk'];
        }

        $total = Db::name($this->name)->where($beans)->count('id');
        return intval($total);
    }

    function info($city_id, $id)
    {
        $selectlist = [
            'id' => 'string',
            'city_id' => 'string',
            'name' => 'string',
            'remark' => 'string',
            'coordinates' => 'array',
            'state' => 'int',
            'creator_id' => 'string',
            'create_time' => 'string',
            'creator_name' => 'string',
            'updater_id' => 'string',
            'update_time' => 'string',
            'updater_name' => 'string',
            'center' => 'array',
            'is_deleted' => 'int',
            'price_rule' => 'array',
        ];
        $beans = [
            'city_id' =>$city_id,
            'id' =>$id
        ];

        $row = $this->where($beans)->filed(common::array_keys($selectlist))->find();

        return $row;
    }

    function update_serva($city_id, $id, $info)
    {
        if(empty($id)) {
            return null;
        }

        $paramlist = [
            'name' => 'string',
            'remark' => 'string',
            'coordinates' => 'array',
            'state' => 'int',
            'price_rule' => 'array',
        ];

        $data = common::type_conver($info, $paramlist);
        $data['update_time'] = date('Y-m-d H:i:s');
        ApiOper::instance()->append_updater_info($data);

        if (isset($data['price_rule'])){
            $price_rule = $data['price_rule'];
            if (is_array($price_rule) && !isset($price_rule['fee_min'])){
                $price_rule['fee_min'] = 1;
            }
            else if (is_array($price_rule) && empty($price_rule['fee_min'])){
                $price_rule['fee_min'] = 1;
            }

            $data['price_rule'] = $price_rule;
        }

        $where = [
            'city_id' => $city_id,
            'id' => $id,
        ];

        self::update($data, $where);

        $this->save_to_mongo($city_id, $id);
        return $data;
    }

    function delete_serva($city_id, $id)
    {
        $data = [
            'is_deleted' => 1,
            'update_time' => date('Y-m-d H:i:s'),
        ];

        ApiOper::instance()->append_updater_info($data);
        $where = [
            'city_id' => $city_id,
            'id' => $id,
        ];

        self::update($data, $where);

        $this->save_to_mongo($city_id, $id);
    }

    var $mongo_field = [
        'city_id' => 'string',
        'id' => 'string',
        'name' => 'string',
        'remark' => 'string',
        'coordinates' => 'array',
        'state' => 'int',
        'creator_id' => 'string',
        'create_time' => 'string',
        'creator_name' => 'string',
        'updater_id' => 'string',
        'update_time' => 'string',
        'updater_name' => 'string',
        'bike_count' => 'int',
        'center' => 'array',
        'is_deleted' => 'int',
        'price_rule' => 'array',
    ];


    function save_to_mongo($city_id, $id)
    {
        $where = [
            'eftype' => EB_TYPE_SERVICE_AREA,
            'city_id' => $city_id,
            'id' => $id,
        ];
        himongo::db()->delete($where);

        $info = (new self())->info($city_id, $id);
        if ($info['state'] == 0 && $info['is_deleted'] == 0) {
            $data = common::type_conver($info, $this->mongo_field);
            $data['eftype'] = EB_TYPE_SERVICE_AREA;
            $data['polygon'] = [
                'type' => 'Polygon',
                'coordinates' => [$info['coordinates']],
            ];

            $data['point'] = [
                'type' => 'Point',
                'coordinates' => $data['center'],
            ];

            himongo::db()->insert($data);
        }
    }

    function is_in($city_id, $coordinate)
    {
        $condition = [
            'eftype' => EB_TYPE_SERVICE_AREA,
        ];
        if (!empty($city_id)) {
            $condition['city_id'] = $city_id;
        }

        $result = himongo::db()->runconmand_intersects($coordinate, $condition, 1);
        foreach ($result as $item) {
            return $item;
        }
        return false;
    }

    function query_list_near($coordinate)
    {
        $condition = [
            'eftype' => EB_TYPE_SERVICE_AREA,
            'state' => 0,
        ];

        $projection = [
            'city_id' => 1,
            'id' => 1,
            'name' => 1,
            'type' => 1,
            'coordinates' => 1,
            'state' => 1,
            'center' => 1,
        ];

        $result = himongo::db()->near($coordinate[0], $coordinate[1], 10 * 1000, 10, $condition, $projection);
        $l = [];
        foreach ($result as $item) {
            $l[] = common::type_conver($item, $this->mongo_field);
        }
        return $l;
    }

    function coordinate_to_city_id($coordinate)
    {
        $svca = $this->is_in(null, $coordinate);
        if (!empty($svca)) {
            return $svca['city_id'];
        }

        $svca = $this->query_list_near($coordinate);

        if (!empty($svca)) {
            return $svca[0]['city_id'];
        }

        return null;
    }

}